/**
 * 
 */
package com.bestbuy.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.bestbuy.pojo.Account;
import com.bestbuy.pojo.AccountRole;
import com.bestbuy.pojo.Bill;
import com.bestbuy.pojo.Catalog;
import com.bestbuy.pojo.FileUploadItem;
import com.bestbuy.pojo.Product;
import com.bestbuy.pojo.ProductDetail;
import com.bestbuy.pojo.Promotion;
import com.bestbuy.service.AccountService;
import com.bestbuy.service.BillService;
import com.bestbuy.service.CatalogService;
import com.bestbuy.service.ProductService;
import com.bestbuy.service.PromotionService;

/**
 * @author lyhoang
 * 
 */
@Controller
public class AdminController {
	@Autowired
	private CatalogService catalogService;
	@Autowired
	private ProductService productService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private BillService billService;
	@Autowired
	private PromotionService promotionService;
	@Autowired
	ServletContext servletContext;

	@RequestMapping(value = { "/admin.do" })
	public String accountView(Model model, Principal principal,
			HttpSession session) {
		List<Catalog> listCatalog = catalogService.getListCatalog();
		model.addAttribute("catalogs", listCatalog);
		List<Product> listProduct = productService.Search("", "0", "1");
		model.addAttribute("products", listProduct);
		String name = "";
		Account account = new Account();
		if (principal != null) {
			if (principal.getName() != null) {
				name = principal.getName();
				session.setAttribute("username", name);
				account = accountService.GetAccount(name);
			}
			if (account != null) {
				if (account.getAccountRole().getRole().equals("Admin")) {
					List<Account> listAccount = accountService.getListAccount();
					model.addAttribute("accounts", listAccount);
					model.addAttribute("isIndex", "SlideShow");
					model.addAttribute("Page", "Admin");
				}
			}
		}
		return "Main";
	}

	@RequestMapping(value = { "/admineditaccount.do" }, method = RequestMethod.GET)
	public String getAccountInfo(Model model,
			@RequestParam(value = "id") String id) {
		Account account = accountService.GetAccount(id);
		model.addAttribute("account", account);
		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("Page", "AdminEditAccount");
		return "Main";
	}

	@RequestMapping(value = { "/admineditaccount.do" }, method = RequestMethod.POST)
	public String updateAccount(Model model,
			@RequestParam(value = "id") String name,
			@RequestParam(value = "username") String username,
			@RequestParam(value = "isdeleted") String isdeleted) {
		Account account = accountService.GetAccount(username);
		// AccountRole accountRole =
		// accountService.getRoleAccount(account.getAccountRole().getRole());
		// accountRole.set
		// account.setUsername(username);
		account.setIsdeleted(Integer.parseInt(isdeleted));
		accountService.updateAccount(account);
		// model.addAttribute("account", account);
		// model.addAttribute("isIndex", "SlideShow");
		// model.addAttribute("Page", "AdminEditAccount");
		return "redirect:/admin.do";
	}

	@RequestMapping(value = { "/productmanagement.do" })
	public String productView(Model model,
			@RequestParam(value = "page") String page,
			@RequestParam(value = "option") String option) {
		//List<Catalog> listCatalog = catalogService.getListCatalog();
		List<Catalog> listCatalog = catalogService.getListCatalogByDeleted("0");
		model.addAttribute("catalogs", listCatalog);
		// List<Product> listProduct = productService.Search("", "0", page);
		if(option.equals("0")){
			List<Product> listProduct = productService.Search("", "0", page);
			model.addAttribute("products", listProduct);
			int totalPage = productService.TotalPage("", "0");
			//int totalPage = productService.countProduct("", "0");
			model.addAttribute("totalPage", totalPage);
			model.addAttribute("isIndex", "SlideShow");
			model.addAttribute("pagecurrent", page);
			model.addAttribute("Page", "AdminProduct");
		}else if (option.equals("1")){
			List<Product> listProduct = productService.Search("", "0", page, "0");
			model.addAttribute("products", listProduct);
			// int totalPage = productService.TotalPage("", "0");
			int totalPage = productService.countProduct("", "0", "0");
			model.addAttribute("totalPage", totalPage);
			model.addAttribute("isIndex", "SlideShow");
			model.addAttribute("pagecurrent", page);
			model.addAttribute("Page", "AdminProduct");
		}else{
			List<Product> listProduct = productService.Search("", "0", page, "1");
			model.addAttribute("products", listProduct);
			//int totalPage = productService.TotalPage("", "0");
			int totalPage = productService.countProduct("", "0", "1");
			model.addAttribute("totalPage", totalPage);
			model.addAttribute("isIndex", "SlideShow");
			model.addAttribute("pagecurrent", page);
			model.addAttribute("Page", "AdminProduct");
		}
		model.addAttribute("option", option);
		return "Main";
	}

	@RequestMapping(value = { "/admineditproduct.do" }, method = RequestMethod.GET)
	public String getProductInfo(Model model,
			@RequestParam(value = "id") String id,
			@RequestParam(value = "action") String action) {
		if (action.equals("Edit")) {
			//List<Catalog> listCatalog = catalogService.getListCatalog();
			List<Catalog> listCatalog = catalogService.getListCatalogByDeleted("0");
			model.addAttribute("catalogs", listCatalog);
			List<Product> listProduct = productService.Search("", "0", "1");
			model.addAttribute("products", listProduct);
			Product product = productService.getProduct(id);
			model.addAttribute("product", product);
			List<Promotion> listPromotion = promotionService.getListPromotion();
			model.addAttribute("promotions", listPromotion);
			model.addAttribute("isIndex", "SlideShow");
			model.addAttribute("Page", "AdminEditProduct");
		}else{
			Product product = productService.getProduct(id);
			product.setIsdeleted(1);
			productService.updateProduct(product);
			//List<Catalog> listCatalog = catalogService.getListCatalog();
			List<Catalog> listCatalog = catalogService.getListCatalogByDeleted("0");
			model.addAttribute("catalogs", listCatalog);
			// List<Product> listProduct = productService.Search("", "0", page);
			List<Product> listProduct = productService.Search("", "0", "1", "0");
			model.addAttribute("products", listProduct);
			// int totalPage = productService.TotalPage("", "0");
			int totalPage = productService.countProduct("", "0", "0");
			model.addAttribute("totalPage", totalPage);
			model.addAttribute("isIndex", "SlideShow");
			model.addAttribute("pagecurrent", "1");
			model.addAttribute("Page", "AdminProduct");		
		}
		return "Main";
	}

	@RequestMapping(value = { "/admineditproduct.do" }, method = RequestMethod.POST)
	public String updateProduct(Model model,
			@RequestParam(value = "id") String id,
			@RequestParam(value = "product") String username,
			@RequestParam(value = "detail") String detail,
			@RequestParam(value = "price") String price,
			@RequestParam(value = "link") String link,
			@RequestParam(value = "quantity") String quantity,
			@RequestParam(value = "idcatogory") String catalogid,
			@RequestParam(value = "idpromotion") String idpromotion) {
		//List<Catalog> listCatalog = catalogService.getListCatalog();
		List<Catalog> listCatalog = catalogService.getListCatalogByDeleted("0");
		model.addAttribute("catalogs", listCatalog);
		List<Product> listProduct = productService.Search("", "0", "1");
		model.addAttribute("products", listProduct);
		Product product = productService.getProduct(id);
		product.setIdproduct(Integer.parseInt(id));
		product.setProductname(username);
		ProductDetail productdetail = product.getProductdetail();
		productdetail.setDetail(detail);
		product.setProductdetail(productdetail);
		product.setPrice(Float.parseFloat(price));
		product.setQuantity(Integer.parseInt(quantity));
		product.setLinkImage(link);
		Catalog catalog = new Catalog();
		catalog = catalogService.getCatalogByCatalogID(catalogid);
		product.setCatalog(catalog);
		Promotion promotion = promotionService.getPromotion(idpromotion);
		product.setPromotion(promotion);
		productService.updateProduct(product);
		List<Promotion> listPromotion = promotionService.getListPromotion();
		model.addAttribute("promotions", listPromotion);
		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("Page", "AdminEditProduct");
		return "redirect:/productmanagement.do?page=1";
	}

	@RequestMapping(value = { "/adminaddproduct.do" })
	public String addproductView(Model model) {
		//List<Catalog> listCatalog = catalogService.getListCatalog();
		List<Catalog> listCatalog = catalogService.getListCatalogByDeleted("0");
		model.addAttribute("catalogs", listCatalog);
		List<Product> listProduct = productService.Search("", "0", "1");
		model.addAttribute("products", listProduct);

		List<Promotion> listPromotion = promotionService.getListPromotion();
		model.addAttribute("promotions", listPromotion);
		model.addAttribute("isIndex", "SlideShow");

		model.addAttribute("Page", "AdminAddProduct");
		return "Main";
	}

	@RequestMapping(value = { "/adminaddproduct.do" }, method = RequestMethod.POST)
	public String addProduct(@RequestParam("file") CommonsMultipartFile file,
			Model model, HttpServletRequest request,
			@RequestParam(value = "id") String id,
			@RequestParam(value = "product") String username,
			@RequestParam(value = "detail") String detail,
			@RequestParam(value = "price") String price,
			@RequestParam(value = "quantity") String quantity,
			@RequestParam(value = "idcatogory") String catalogid,
			@RequestParam(value = "idpromotion") String idpromotion) {
		try {
			// MultipartHttpServletRequest multipartRequest =
			// (MultipartHttpServletRequest) request;
			MultipartFile filea = file;
			InputStream inputStream = null;
			OutputStream outputStream = null;
			if (filea.getSize() > 0) {
				inputStream = filea.getInputStream();
				// File realUpload = new File("C:/");
				String webappRoot = servletContext.getRealPath("/");
				String filename = webappRoot + File.separator + "resources"
						+ File.separator + "images" + File.separator
						+ "product" + File.separator
						+ filea.getOriginalFilename();
				outputStream = new FileOutputStream(filename);
				System.out.println("====22=========");
				System.out.println(filea.getOriginalFilename());
				System.out.println("=============");
				int readBytes = 0;
				byte[] buffer = new byte[8192];
				while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
					System.out.println("===ddd=======");
					outputStream.write(buffer, 0, readBytes);
				}
				outputStream.close();
				inputStream.close();
				ProductDetail productdetail = new ProductDetail();
				productdetail.setDetail(detail);
				productdetail.setRate(0);
				productdetail.setView(0);
				Product product = new Product();
				product.setProductname(username);
				product.setPrice(Float.parseFloat(price));
				product.setProductdetail(productdetail);
				product.setQuantity(Integer.parseInt(quantity));
				product.setLinkImage("/resources/images/product/"
						+ filea.getOriginalFilename());
				product.setIsdeleted(0);
				Catalog catalog = new Catalog();
				catalog = catalogService.getCatalogByCatalogID(catalogid);
				product.setCatalog(catalog);
				Promotion promotion = promotionService
						.getPromotion(idpromotion);
				product.setPromotion(promotion);
				// productService.saveProduct(product);
				// product = productService.getProductByName(username);
				// product.setProductdetail(productdetail);
				productdetail.setProduct(product);
				// productService.saveProductDetail(productdetail);

				productService.saveProduct(product);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		//List<Catalog> listCatalog = catalogService.getListCatalog();
		List<Catalog> listCatalog = catalogService.getListCatalogByDeleted("0");
		model.addAttribute("catalogs", listCatalog);
		List<Product> listProduct = productService.Search("", "0", "1");
		model.addAttribute("products", listProduct);
		int totalPage = productService.TotalPage("", "0");
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("pagecurrent", "1");
		model.addAttribute("Page", "AdminProduct");
		return "Main";
	}

	@RequestMapping(value = { "/admincatalog.do" })
	public String catalogView(Model model,
			@RequestParam(value = "page") String page,
			@RequestParam(value = "option") String option) {
		if(option.equals("0")){
			List<Catalog> listCatalog = catalogService.getListCatalog(page);
			model.addAttribute("catalogs", listCatalog);	
			// List<Product> listProduct = productService.Search("", "0", "1");
			// model.addAttribute("products", listProduct);
			int totalPage = catalogService.countCatalog();
			model.addAttribute("totalPage", totalPage);
			model.addAttribute("isIndex", "SlideShow");
			model.addAttribute("pagecurrent", page);
			model.addAttribute("Page", "AdminCatalog");
		}else if(option.equals("1")){
			List<Catalog> listCatalog = catalogService.getListCatalog(page, "0");
			model.addAttribute("catalogs", listCatalog);	
			// List<Product> listProduct = productService.Search("", "0", "1");
			// model.addAttribute("products", listProduct);
			int totalPage = catalogService.countCatalog("0");
			model.addAttribute("totalPage", totalPage);
			model.addAttribute("isIndex", "SlideShow");
			model.addAttribute("pagecurrent", page);
			model.addAttribute("Page", "AdminCatalog");
		}else{
			List<Catalog> listCatalog = catalogService.getListCatalog(page, "1");
			model.addAttribute("catalogs", listCatalog);	
			// List<Product> listProduct = productService.Search("", "0", "1");
			// model.addAttribute("products", listProduct);
			int totalPage = catalogService.countCatalog("1");
			model.addAttribute("totalPage", totalPage);
			model.addAttribute("isIndex", "SlideShow");
			model.addAttribute("pagecurrent", page);
			model.addAttribute("Page", "AdminCatalog");
		}
		model.addAttribute("option", option);
		return "Main";
	}

	@RequestMapping(value = { "/adminaddcatalog.do" })
	public String addCatalogView(Model model) {
		List<Catalog> listCatalog = catalogService.getListCatalog();
		model.addAttribute("catalogs", listCatalog);

		model.addAttribute("isIndex", "SlideShow");

		model.addAttribute("Page", "AdminAddCatalog");
		return "Main";
	}

	@RequestMapping(value = { "/adminaddcatalog.do" }, method = RequestMethod.POST)
	public String addCatalog(Model model, HttpServletRequest request,
			@RequestParam(value = "id") String id,
			@RequestParam(value = "catalogcode") String code,
			@RequestParam(value = "catalogname") String name) {

		Catalog catalog = new Catalog();
		catalog.setCatalogcode(code);
		catalog.setCatalogname(name);
		catalogService.addCatalog(catalog);
		List<Catalog> listCatalog = catalogService.getListCatalog("1");
		model.addAttribute("catalogs", listCatalog);

		// List<Product> listProduct = productService.Search("", "0", "1");
		// model.addAttribute("products", listProduct);
		int totalPage = catalogService.countCatalog();
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("pagecurrent", "1");
		model.addAttribute("Page", "AdminCatalog");
		return "Main";
	}

	@RequestMapping(value = { "/billmanagement.do" })
	public String billView(Model model,
			@RequestParam(value = "page") String page,
			@RequestParam(value = "option") String option) {
		List<Catalog> listCatalog = catalogService.getListCatalog();
		model.addAttribute("catalogs", listCatalog);
		List<Bill> billList = new ArrayList<Bill>();
		int totalPage = billService.countAllBill();
		if (option.equals("1")) {
			billList = billService.getBillIsNotPaid("0", page);
			totalPage = billService.countAllBill("0");
		} else if (option.equals("2")) {
			billList = billService.getBillIsNotPaid("1", page);
			totalPage = billService.countAllBill("1");
		} else if (option.equals("0")) {
			billList = billService.getAllBill(page);
			totalPage = billService.countAllBill();
		}

		model.addAttribute("bills", billList);
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("pagecurrent", page);
		model.addAttribute("Page", "AdminBill");
		return "Main";
	}

	@RequestMapping(value = { "/adminpaidbill.do" })
	public String billPaid(Model model,
			@RequestParam(value = "id") String idBill) {
		List<Catalog> listCatalog = catalogService.getListCatalog();
		model.addAttribute("catalogs", listCatalog);
		Bill bill = billService.getBill(idBill);
		bill.setIspaid(1);
		billService.updateBill(bill);
		List<Bill> billList = new ArrayList<Bill>();
		int totalPage = billService.countAllBill();
		// if (option.equals("1")) {
		// billList = billService.getBillIsNotPaid("0", page);
		// totalPage = billService.countAllBill("0");
		// } else if (option.equals("2")) {
		// billList = billService.getBillIsNotPaid("1", page);
		// totalPage = billService.countAllBill("1");
		// } else if (option.equals("0")){
		// billList = billService.getAllBill(page);
		// totalPage = billService.countAllBill();
		// }
		billList = billService.getBillIsNotPaid("0", "1");
		totalPage = billService.countAllBill("0");
		model.addAttribute("bills", billList);
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("pagecurrent", "1");
		model.addAttribute("Page", "AdminBill");
		return "Main";
	}

	@RequestMapping(value = { "/promotionmanagement.do" })
	public String promotionView(Model model,
			@RequestParam(value = "page") String page) {
		List<Catalog> listCatalog = catalogService.getListCatalog();
		model.addAttribute("catalogs", listCatalog);
		List<Promotion> promotionList = new ArrayList<Promotion>();
		int totalPage = promotionService.countProduct();
		promotionList = promotionService.getListPromotion(page);
		model.addAttribute("promotions", promotionList);
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("pagecurrent", page);
		model.addAttribute("Page", "AdminPromotion");
		return "Main";
	}

	@RequestMapping(value = { "/adminaddpromotion.do" })
	public String addPromotionView(Model model) {
		List<Catalog> listCatalog = catalogService.getListCatalog();
		model.addAttribute("catalogs", listCatalog);

		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("Page", "AdminAddPromotion");
		return "Main";
	}

	@RequestMapping(value = { "/adminaddpromotion.do" }, method = RequestMethod.POST)
	public String addPromotion(Model model, HttpServletRequest request,
			@RequestParam(value = "id") String id,
			@RequestParam(value = "discount") String discount) {
		Promotion promotion = new Promotion();
		promotion.setDiscount(Float.parseFloat(discount));
		promotionService.savePromotion(promotion);
		List<Catalog> listCatalog = catalogService.getListCatalog();
		model.addAttribute("catalogs", listCatalog);
		List<Promotion> promotionList = new ArrayList<Promotion>();
		int totalPage = promotionService.countProduct();
		promotionList = promotionService.getListPromotion("1");
		model.addAttribute("promotions", promotionList);
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("pagecurrent", "1");
		model.addAttribute("Page", "AdminPromotion");
		return "Main";
	}

	@RequestMapping(value = { "/admineditcatalog.do" })
	public String updateCatalogView(Model model,
			@RequestParam(value = "id") String id,
			@RequestParam(value = "action") String action) {
		if (action.equals("Edit")) {
			List<Catalog> listCatalog = catalogService.getListCatalog("1");
			model.addAttribute("catalogs", listCatalog);
			Catalog catalog = catalogService.getCatalogByCatalogID(id);
			model.addAttribute("catalog", catalog);
			model.addAttribute("isIndex", "SlideShow");

			model.addAttribute("Page", "AdminEditCatalog");
		} else if (action.equals("Delete")) {
			Catalog catalog = catalogService.getCatalogByCatalogID(id);
			catalog.setIsdeleted(1);
			catalogService.deleteCatalog(catalog);
			List<Catalog> listCatalog = catalogService.getListCatalog("1");
			model.addAttribute("catalogs", listCatalog);

			// List<Product> listProduct = productService.Search("", "0", "1");
			// model.addAttribute("products", listProduct);
			int totalPage = catalogService.countCatalog();
			model.addAttribute("totalPage", totalPage);
			model.addAttribute("isIndex", "SlideShow");
			model.addAttribute("pagecurrent", "1");
			model.addAttribute("Page", "AdminCatalog");
		}
		return "Main";
	}

	@RequestMapping(value = { "/admineditcatalog.do" }, method = RequestMethod.POST)
	public String updateCatalog(Model model, HttpServletRequest request,
			@RequestParam(value = "id") String id,
			@RequestParam(value = "catalogcode") String code,
			@RequestParam(value = "catalogname") String name) {
		Catalog catalog = catalogService.getCatalogByCatalogID(id);
		catalog.setCatalogname(name);
		catalog.setCatalogcode(code);
		catalogService.updateCatalog(catalog);
		List<Catalog> listCatalog = catalogService.getListCatalog("1");
		model.addAttribute("catalogs", listCatalog);

		// List<Product> listProduct = productService.Search("", "0", "1");
		// model.addAttribute("products", listProduct);
		int totalPage = catalogService.countCatalog();
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("isIndex", "SlideShow");
		model.addAttribute("pagecurrent", "1");
		model.addAttribute("Page", "AdminCatalog");
		return "Main";
	}
}
